package com.webchat.act.service;


import com.webchat.common.constants.ResourceBehaviorConstants;
import com.webchat.common.util.SpringContextUtil;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;

import java.util.HashMap;
import java.util.Map;

@Component
public class ResourceBehaviorFactory implements InitializingBean , ApplicationContextAware {

    private ApplicationContext applicationContext;
    private static final Map<String, AbstractResourceBehaviorService> serviceMap = new HashMap<>();

    @Override
    public void afterPropertiesSet() throws Exception {
        this.initServiceMap();
    }

    private void initServiceMap() {

        serviceMap.put(ResourceBehaviorConstants.BehaviorType.LIKE.name(), new TwoWayResourceBehaviorService());
        serviceMap.put(ResourceBehaviorConstants.BehaviorType.COLLECT.name(), new TwoWayResourceBehaviorService());
        serviceMap.put(ResourceBehaviorConstants.BehaviorType.SHARE.name(), new OneWayResourceBehaviorService());
        serviceMap.put(ResourceBehaviorConstants.BehaviorType.VIEW.name(), new OneWayResourceBehaviorService());
    }

    public static AbstractResourceBehaviorService getService(String behaviorType) {

        AbstractResourceBehaviorService abstractResourceBehaviorService = serviceMap.get(behaviorType);
        Assert.notNull(abstractResourceBehaviorService, "不支持的互动行为");
        abstractResourceBehaviorService.setBehaviorType(behaviorType);
        return abstractResourceBehaviorService;
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
}
